//
//  CXLPhotoBrowserViewController.swift
//  weibo1990
//
//  Created by 曹晓龙 on 15/10/26.
//  Copyright © 2015年 曹晓龙. All rights reserved.
//

import UIKit
import SVProgressHUD

/// cell 重用标示
let CXLPhotoBrowserViewCellID = "CXLPhotoBrowserViewCellID"

/// 图片查看视图
class CXLPhotoBrowserViewController: UIViewController {

    /// 传入的选中照片索引
    var indexPh:NSIndexPath
    
    /// url数组
    var urls:[NSURL]
    
    //MARK: - 监听方法
    ///  关闭查看视图
    @objc private func close(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    ///  保存图片
    @objc private func save(){
        
        let cell = collectionView.visibleCells()[0] as! CXLPhotoBrowserViewCell
        
        let image = cell.imgView.image

        if image == nil {
            return
        }
        
        UIImageWriteToSavedPhotosAlbum(image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;

    ///  保存照片的回调
    ///
    ///  - parameter image:       要保存的照片
    ///  - parameter error:       错误
    ///  - parameter contextInfo: 上下文
    @objc private func image(image:UIImage, didFinishSavingWithError error:NSError?, contextInfo:AnyObject?){
        
        let message = error == nil ? "保存成功" : "保存失败"
        
        SVProgressHUD.showInfoWithStatus(message)

    }
    
    //MARK: -构造函数
    init(indexPath:NSIndexPath, urls:[NSURL]){
        
        self.indexPh = indexPath
        
        self.urls = urls
        
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK: - 视图生命周期
    override func loadView() {
        
        var rect = UIScreen.mainScreen().bounds
        
        rect.size.width += 20
        
        view = UIView(frame: rect)
        
        setupUI()
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 开始时,滚动到选择的图片对应的大图
        collectionView.scrollToItemAtIndexPath(indexPh, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
        
    }


    //MARK: - 懒加载控键
    ///collectionView - 存放放大的图片
    lazy var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: CXLCollectionViewLayout())
    /// 关闭按钮
    private lazy var closeBtn:UIButton = UIButton(title: "关闭", backImageName: nil, backColor: UIColor.darkGrayColor(), titleColor: UIColor.whiteColor())
    /// 保存图片按钮
    private lazy var saveBtn:UIButton = UIButton(title: "保存", backImageName: nil, backColor: UIColor.darkGrayColor(), titleColor: UIColor.whiteColor())
    
    //MARK: - 定义Cell流水布局
    class CXLCollectionViewLayout: UICollectionViewFlowLayout {
        
        override func prepareLayout() {
            
            super.prepareLayout()
            
            itemSize = collectionView!.bounds.size
            
            minimumInteritemSpacing = 0
            
            minimumLineSpacing = 0
            
            scrollDirection = .Horizontal
            
            collectionView?.showsHorizontalScrollIndicator = false
            
            collectionView?.pagingEnabled = true
            
            collectionView?.bounces = false
            
            collectionView?.backgroundColor = UIColor.blackColor()
        }
    }
}

// MARK: - 设置界面
extension CXLPhotoBrowserViewController {
    
    ///  设置UI
    private func setupUI(){
        //添加控键
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        
        // 设置布局
        collectionView.frame = view.bounds
        
        closeBtn.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left).offset(8)
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        saveBtn.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(view.snp_right).offset(-28)
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        prepareForCollectionView()
        
        // 监听方法
        
        closeBtn.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        saveBtn.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    ///  准备collectionView
    private func prepareForCollectionView(){
        
        collectionView.registerClass(CXLPhotoBrowserViewCell.self, forCellWithReuseIdentifier: CXLPhotoBrowserViewCellID)
        collectionView.dataSource = self
        collectionView.delegate = self
    }
}

// MARK: - collectionView代理方法和数据源方法
extension CXLPhotoBrowserViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CXLPhotoBrowserViewCellID, forIndexPath: indexPath) as! CXLPhotoBrowserViewCell
        
        cell.url = urls[indexPath.item]
        
//        cell.backgroundColor = UIColor.blackColor()
        
        cell.photoCellDelegate = self
        
        return cell
    }
}

// MARK: - dismiss 时遵循的转场动画代理
extension CXLPhotoBrowserViewController:CXLTransitionDismissDelegate {
    
    ///  转场动画 大米 图片
    func imageViewForTranstionDismiss() -> UIImageView {
        
        let cell = collectionView.visibleCells()[0] as! CXLPhotoBrowserViewCell
        
        let iv = UIImageView()
        
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        
        iv.image = cell.imgView.image
        
        let rect = cell.scrollView.convertRect(cell.imgView.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        iv.frame = rect
        
        return iv
    }
    
    ///  转场动画结束时图片所在的索引
    func indexPathForTranstionDismiss() -> NSIndexPath {
        
        let cell = collectionView.visibleCells()[0] as! CXLPhotoBrowserViewCell
        
        let indexPath = collectionView.indexPathForCell(cell)!
        
        return indexPath
    }
}

// MARK: - CXLPhotoBrowserCellDelegate 点击图片关闭视图的代理
extension CXLPhotoBrowserViewController:CXLPhotoBrowserCellDelegate {
    
    ///  交互式转场动画
    func photoBrowserCellPictureScale(scale: CGFloat) {
        
        let isHidden = (scale < 1)
        
        hiddenCollectionView(isHidden)
        
        if isHidden {
            
            collectionView.transform = CGAffineTransformMakeScale(scale, scale)
            
        }else if scale > 1 {
            
            collectionView.transform = CGAffineTransformIdentity
        }
        
    }
    
    ///  设置缩放时,各按钮的状态
    ///
    ///  - parameter isHidden: <#isHidden description#>
    private func hiddenCollectionView(isHidden:Bool){
        
        collectionView.backgroundColor = isHidden ? UIColor.clearColor() : UIColor.blackColor()
        
        saveBtn.hidden = isHidden
        closeBtn.hidden = isHidden
    }
    
    ///  点击图片,关闭图片浏览器
    func photoBrowserCellClickDismissPicture() {
        
        close()
    }
}
